<template>
  <ElDialog
    v-model="visible"
    draggable
    :title="isEdit ? '编辑驿站' : '新增驿站'"
    width="800px"
    top="4vh"
    :close-on-click-modal="false"
    @open="handleOpen"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="驿站名称" prop="restName">
            <ElInput
              v-model="form.restName"
              placeholder="请输入驿站名称"
              maxlength="30"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="上架状态" prop="restUpFlag">
            <ElSelect v-model="form.restUpFlag" placeholder="请选择上架状态">
              <ElOption label="隐藏" :value="1" />
              <ElOption label="显示" :value="2" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="是否是兑换点" prop="restScoFlag">
            <ElSelect v-model="form.restScoFlag" placeholder="请选择兑换点">
              <ElOption label="是" :value="2" />
              <ElOption label="否" :value="1" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="驿站地址" prop="restAddress">
            <div class="flex items-center w-full">
              <div class="flex-1">
                <el-input v-model="form.restAddress" placeholder="请输入驿站地址" />
              </div>
              <el-button class="ml-2" @click="openMapSelection">
                <el-icon>
                  <Location />
                </el-icon>
              </el-button>
            </div>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="联系方式" prop="restPhone">
            <ElInput v-model="form.restPhone" placeholder="请输入联系方式" maxlength="20" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="24小时开放" prop="restLongOpenFlag">
            <ElSelect v-model="form.restLongOpenFlag" placeholder="请选择开放方式">
              <ElOption label="定时开放" :value="1" />
              <ElOption label="24小时开放" :value="2" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20" v-if="form.restLongOpenFlag === 1">
        <ElCol :span="24">
          <ElFormItem label="开放时间" prop="restOpenTime">
            <div class="flex items-center gap-2 w-full">
              <el-time-select
                v-model="startTime"
                :max-time="endTime"
                placeholder="请选择开始时间"
                start="06:00"
                step="00:15"
                end="22:00"
              />
              <el-time-select
                v-model="endTime"
                :min-time="startTime"
                placeholder="请选择结束时间"
                start="06:00"
                step="00:15"
                end="22:00"
              />
            </div>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="驿站介绍" prop="restInfo">
            <ElInput
              v-model="form.restInfo"
              placeholder="请输入驿站介绍"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="驿站图片" prop="restPhoto">
            <proUploadImg
              v-model:fileList="restPhoto"
              action="/api/api/ossFile/saveFile"
              :maxSize="10"
              tip="图片大小不超过20MB"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <!-- 服务内容管理 -->
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="服务内容" prop="geoRestServeList">
            <div>
              <VueDraggable
                v-model="form.geoRestServeList"
                :disabled="false"
                :prevent-on-filter="false"
                handle=".drag-handle"
              >
                <ElFormItem
                  v-for="(service, index) in form.geoRestServeList"
                  :key="service.serveSort"
                  :prop="'geoRestServeList.' + index + '.serveName'"
                  class="service-item"
                  :rules="{
                    required: true,
                    message: '服务内容不能为空',
                    trigger: 'blur'
                  }"
                >
                  <div class="flex items-center flex-col gap-2">
                    <div class="flex items-center gap-2 mb-2">
                      <!-- 拖拽手柄 -->
                      <div class="drag-handle cursor-move flex items-center text-gray-400">
                        <el-icon><Rank /></el-icon>
                      </div>
                      <!-- 序号 -->
                      <span class="w-6 text-center">{{ index + 1 }}</span>
                      <ElInput
                        v-model="service.serveName"
                        placeholder="请输入服务内容"
                        maxlength="10"
                        size="small"
                      />
                      <ElButton
                        type="danger"
                        size="small"
                        :icon="Delete"
                        @click="removeService(index)"
                      >
                        删除
                      </ElButton>
                    </div>
                  </div>
                </ElFormItem>
              </VueDraggable>
              <div>
                <ElButton type="primary" :icon="Plus" size="small" @click="addService">
                  添加服务
                </ElButton>
              </div>
            </div>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">取消</ElButton>
        <ElButton type="primary" :loading="loading" @click="handleSubmit"> 确定 </ElButton>
      </div>
    </template>
  </ElDialog>

  <MapSelection
    ref="mapSelectionRef"
    :title="mapSelectionDialog.title"
    :visible="mapSelectionDialog.visible"
    @getLocationSuccess="handleLocationSuccess"
    @mapClose="mapSelectionDialog.visible = false"
  />
</template>

<script setup lang="ts">
  import { ref, computed, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Plus, Delete, Rank } from '@element-plus/icons-vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { geoRestSaveDataUsingPost, GeoRestVo, geoRestUpdateDateUsingPost } from '@/api'
  import MapSelection from '@/components/core/map/index.vue'
  import { VueDraggable } from 'vue-draggable-plus'
  import { clone } from 'xe-utils'
  import { mobile } from '@/utils/test'

  // 类型定义
  interface Props {
    modelValue: boolean
    restData?: GeoRestVo | null
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  // Props 和 Emits
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    restData: undefined
  })

  const emit = defineEmits<Emits>()

  // 响应式数据
  const formRef = ref<FormInstance>()

  const loading = ref(false)

  const restPhoto = ref([])

  const startTime = ref('')
  const endTime = ref('')

  const initForm: GeoRestVo = {
    restName: '',
    restAddress: '',
    restLongitude: '',
    restLatitude: '',
    restPhone: '',
    restLongOpenFlag: 1,
    restOpenTime: '',
    restUpFlag: 2,
    restScoFlag: 1,
    restInfo: '',
    restPhoto: '',
    geoRestServeList: []
  }

  const form = ref<GeoRestVo>(clone(initForm, true))

  // 计算属性
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  const isEdit = computed(() => !!props.restData?.id)

  // 表单验证规则
  const rules: FormRules = {
    restName: [
      { required: true, message: '请输入驿站名称', trigger: 'blur' },
      { max: 30, message: '驿站名称不能超过30个字符', trigger: 'blur' }
    ],
    restAddress: [
      { required: true, message: '请输入驿站地址', trigger: ['blur', 'change'] },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请输入驿站地址'))
            return
          }
          // 校验经度和纬度
          if (!form.value.restLongitude || !form.value.restLatitude) {
            callback(new Error('请选择驿站位置（经度和纬度）'))
            return
          }
          callback()
        },
        trigger: ['blur', 'change']
      }
    ],
    restPhone: [
      {
        required: true,
        message: '请输入联系方式',
        trigger: 'blur',
        validator: (rule, value, callback) => {
          if (!mobile(value)) {
            callback(new Error('请输入正确的联系方式'))
            return
          }
          callback()
        }
      }
    ],
    restLongOpenFlag: [{ required: true, message: '请选择开放方式', trigger: 'change' }],
    restOpenTime: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (form.value.restLongOpenFlag === 1 && (!startTime.value || !endTime.value)) {
            callback(new Error('请选择开放时间'))
            return
          }
          callback()
        },
        trigger: ['blur', 'change']
      }
    ],
    restPhoto: [
      {
        required: true,
        message: '请上传驿站图片',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (restPhoto.value.length === 0) {
            callback(new Error('请上传驿站图片'))
            return
          }
          callback()
        }
      }
    ],
    restUpFlag: [{ required: true, message: '请选择上架状态', trigger: 'change' }],
    restScoFlag: [{ required: true, message: '请选择兑换点', trigger: 'change' }],
    restInfo: [{ max: 500, message: '驿站介绍不能超过500个字符', trigger: 'blur' }]
  }

  const mapSelectionRef = ref()

  const mapSelectionDialog = ref({
    visible: false,
    title: '选择位置'
  })

  // 打开地图选择
  const openMapSelection = () => {
    //初始化地图的经纬度，还有地址
    mapSelectionRef.value.initMapLatLng({
      longitude: form.value.restLongitude || '114.3203',
      latitude: form.value.restLatitude || '30.3505',
      address: form.value.restAddress
    })
    mapSelectionDialog.value.visible = true
  }

  // 获取位置成功
  const handleLocationSuccess = (location: any) => {
    form.value.restLongitude = location.longitude
    form.value.restLatitude = location.latitude
    form.value.restAddress = location.address
    mapSelectionDialog.value.visible = false
  }

  const addService = () => {
    form.value.geoRestServeList?.push({
      serveName: '',
      serveSort: form.value.geoRestServeList?.length + 1
    })
  }

  const removeService = (index: number) => {
    form.value.geoRestServeList?.splice(index, 1)
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      loading.value = true
      if (isEdit.value) {
        await geoRestUpdateDateUsingPost({
          body: {
            ...form.value,
            restPhoto: JSON.stringify(restPhoto.value),
            geoRestServeList: form.value.geoRestServeList?.map((item, index) => ({
              serveName: item.serveName,
              serveSort: index + 1
            })),
            restOpenTime: `${startTime.value}-${endTime.value}`
          }
        })
      } else {
        await geoRestSaveDataUsingPost({
          body: {
            ...form.value,
            restPhoto: JSON.stringify(restPhoto.value),
            geoRestServeList: form.value.geoRestServeList?.map((item, index) => ({
              serveName: item.serveName,
              serveSort: index + 1
            })),
            restOpenTime: `${startTime.value}-${endTime.value}`
          }
        })
      }

      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      emit('success')
    } finally {
      loading.value = false
    }
  }

  const handleOpen = () => {
    if (isEdit.value) {
      restPhoto.value = JSON.parse(props.restData?.restPhoto || '[]')
      nextTick(() => {
        form.value = clone(props.restData as GeoRestVo, true)
        if (form.value.restOpenTime) {
          const timeArr = form.value.restOpenTime.split('-')
          startTime.value = timeArr[0]
          endTime.value = timeArr[1]
          console.log(timeArr, 115)
        }
      })
    } else {
      form.value = clone(initForm, true)
    }
  }

  const handleClose = () => {
    formRef.value?.resetFields()
    restPhoto.value = []
    nextTick(() => {
      visible.value = false
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.service-item) {
    .el-form-item__content {
      .el-form-item__error {
        margin-top: -12px;
        margin-left: 46px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
</style>
